/*circle-progress js*/

function filterFn(){
    (function($) {
        function CircleProgress(config) {
            this.init(config);
        }
        CircleProgress.prototype = {
            value: 0.0,
            size: 140.0,
            thickness: 'auto',
            fill: {
                gradient: ['#3aeabb', '#fdd250']
            },
            emptyFill: '#e6e6e6',
            animation: {
                duration: 1200,
                easing: 'circleProgressEasing'
            },
            animationStartValue: 0.0,
            reverse: false,
            lineCap: 'butt',
            constructor: CircleProgress,
            el: null,
            canvas: null,
            ctx: null,
            radius: 0.0,
            arcFill: null,
            lastFrameValue: 0.0,
            init: function(config) {
                $.extend(this, config);
                this.radius = this.size / 2;
                this.initWidget();
                this.initFill();
                this.draw();
            },
            initWidget: function() {
                var canvas = this.canvas = this.canvas || $('<canvas>').prependTo(this.el)[0];
                canvas.width = this.size;
                canvas.height = this.size;
                this.ctx = canvas.getContext('2d');
            },
            initFill: function() {
                var self = this,
                    fill = this.fill,
                    ctx = this.ctx,
                    size = this.size;

                if (!fill)
                    throw Error("The fill is not specified!");

                if (fill.color)
                    this.arcFill = fill.color;

                if (fill.gradient) {
                    var gr = fill.gradient;

                    if (gr.length == 1) {
                        this.arcFill = gr[0];
                    } else if (gr.length > 1) {
                        var ga = fill.gradientAngle || 0, // gradient direction angle; 0 by default
                            gd = fill.gradientDirection || [
                                size / 2 * (1 - Math.cos(ga)), // x0
                                size / 2 * (1 + Math.sin(ga)), // y0
                                size / 2 * (1 + Math.cos(ga)), // x1
                                size / 2 * (1 - Math.sin(ga))  // y1
                            ];

                        var lg = ctx.createLinearGradient.apply(ctx, gd);

                        for (var i = 0; i < gr.length; i++) {
                            var color = gr[i],
                                pos = i / (gr.length - 1);

                            if ($.isArray(color)) {
                                pos = color[1];
                                color = color[0];
                            }

                            lg.addColorStop(pos, color);
                        }

                        this.arcFill = lg;
                    }
                }
                function setImageFill() {
                    var bg = $('<canvas>')[0];
                    bg.width = self.size;
                    bg.height = self.size;
                    bg.getContext('2d').drawImage(img, 0, 0, size, size);
                    self.arcFill = self.ctx.createPattern(bg, 'no-repeat');
                    self.drawFrame(self.lastFrameValue);
                }
            },
            draw: function() {
                if (this.animation)
                    this.drawAnimated(this.value);
                else
                    this.drawFrame(this.value);
            },
            drawFrame: function(v) {
                this.lastFrameValue = v;
                this.ctx.clearRect(0, 0, this.size, this.size);
                this.drawEmptyArc(v);
                this.drawArc(v);
            },
            drawArc: function(v) {
                var ctx = this.ctx,
                    r = this.radius,
                    t = this.getThickness(),
                    a = this.startAngle;

                ctx.save();
                ctx.beginPath();

                if (!this.reverse) {
                    ctx.arc(r, r, r - t / 2, a, a + Math.PI * 2 * v);
                } else {
                    ctx.arc(r, r, r - t / 2, a - Math.PI * 2 * v, a);
                }

                ctx.lineWidth = t;
                ctx.lineCap = this.lineCap;
                ctx.strokeStyle = this.arcFill;
                ctx.stroke();
                ctx.restore();
            },
            drawEmptyArc: function(v) {
                var ctx = this.ctx,
                    r = this.radius,
                    t = this.getThickness(),
                    a = this.startAngle;

                if (v < 1) {
                    ctx.save();
                    ctx.beginPath();

                    if (v <= 0) {
                        ctx.arc(r, r, r - t / 2, 0, Math.PI * 2);
                    } else {
                        if (!this.reverse) {
                            ctx.arc(r, r, r - t / 2, a + Math.PI * v, a);
                        } else {
                            ctx.arc(r, r, r - t / 2, a, a - Math.PI * v);
                        }
                    }

                    ctx.lineWidth = t;
                    ctx.strokeStyle = this.emptyFill;
                    ctx.stroke();
                    ctx.restore();
                }
            },
            drawAnimated: function(v) {
                var self = this,
                    el = this.el;

                el.trigger('circle-animation-start');

                $(this.canvas)
                    .stop(true, true)
                    .css({ animationProgress: 0 })
                    .animate({ animationProgress: 1 }, $.extend({}, this.animation, {
                        step: function(animationProgress) {
                            var stepValue = self.animationStartValue * (1 - animationProgress) + v * animationProgress;
                            self.drawFrame(stepValue);
                            el.trigger('circle-animation-progress', [animationProgress, stepValue]);
                        },
                        complete: function() {
                            el.trigger('circle-animation-end');
                        }
                    }));
            },
            getThickness: function() {
                return $.isNumeric(this.thickness) ? this.thickness : this.size / 14;
            }
        };

        $.circleProgress = {
            // Default options (you may override them)
            defaults: CircleProgress.prototype
        };

        // ease-in-out-cubic
        $.easing.circleProgressEasing = function(x, t, b, c, d) {
            if ((t /= d / 2) < 1)
                return c / 2 * t * t * t + b;
            return c / 2 * ((t -= 2) * t * t + 2) + b;
        };

        $.fn.circleProgress = function(config) {
            var dataName = 'circle-progress';

            if (config == 'widget') {
                var data = this.data(dataName);
                return data && data.canvas;
            }

            return this.each(function() {
                var el = $(this),
                    instance = el.data(dataName),
                    cfg = $.isPlainObject(config) ? config : {};

                if (instance) {
                    instance.init(cfg);
                } else {
                    cfg.el = el;
                    instance = new CircleProgress(cfg);
                    el.data(dataName, instance);
                }
            });
        };
    })(jQuery);

    /*滤芯实例 */
    var percent_1 = $(".percent1").val();
    var percent_2 = $(".percent2").val();
    var percent_3 = $(".percent3").val();
    var percent_4 = $(".percent4").val();
    var percent_5 = $(".percent5").val();
    //滤芯1
    $('.first.circle').circleProgress({
        value:percent_1/100,
        startAngle: -Math.PI/3,
        lineCap: 'round',
        fill: { color: '#5dc1cf' }
    }).on('circle-animation-progress', function(event, progress) {
        $(this).find('strong').html(parseInt(percent_1 * progress) + '<i>%</i>');
    });
    //滤芯2
    $('.second.circle').circleProgress({
        value:percent_2/100,
        startAngle: -Math.PI/3,
        lineCap: 'round',
        fill: { color: '#29abe2' }
    }).on('circle-animation-progress', function(event, progress) {
        $(this).find('strong').html(parseInt(percent_2 * progress) + '<i>%</i>');
    });
    //滤芯3
    $('.third.circle').circleProgress({
        value: percent_3/100,
        startAngle: -Math.PI/3,
        lineCap: 'round',
        fill: { color: '#fbb03b' }
    }).on('circle-animation-progress', function(event, progress) {
        $(this).find('strong').html(parseInt(percent_3 * progress) + '<i>%</i>');
    });
    //滤芯4
    $('.forth.circle').circleProgress({
        value:percent_4/100,
        startAngle: -Math.PI/3,
        lineCap: 'round',
        fill: { color: '#f15a24' }
    }).on('circle-animation-progress', function(event, progress) {
        $(this).find('strong').html(parseInt(percent_4 * progress) + '<i>%</i>');
    });
    //滤芯5
    $('.five.circle').circleProgress({
        value:percent_5/100,
        startAngle: -Math.PI/3,
        lineCap: 'round',
        fill: { color: '#8cc63f' }
    }).on('circle-animation-progress', function(event, progress) {
        $(this).find('strong').html(parseInt(percent_5 * progress) + '<i>%</i>');
    }); 

}


//关闭所有动作
function all_hide(){
    $(".add_water").hide();//制水1
    $(".lessWater").hide();//缺水2
    $(".fullWater1").hide();//水满3
    $(".fullWater2").hide();//水满3
    $(".service").hide();//检修4
    $(".wash").hide();//冲洗5
    $(".arrearage").hide();//欠费6
    $(".arrearageText").hide();//欠费6
    $(".textList").hide();//开机状态文本显示
    $(".offTxtBg").hide();//关机7
    $(".leakage_whisht").hide();//漏水8
    $(".leakage_act").hide();//漏水8
    $(".halt").hide();//停机9
}
//制水状态1
function addWater(){
    all_hide();
    $(".add_water").show();
    $(".textList").show();
    $('.washBtn').html("冲洗");
    $(".washBtn").css("backgroundColor","#fff");
    if($(".power_off").html()=="开机"){
        $(".power_off").html("关机");
    }
}
//缺水状态2
function lessWater(){
    all_hide();
    $(".lessWater").show();
    $(".textList").show();
    $('.washBtn').html("冲洗");
    $(".washBtn").css("backgroundColor","#ccc");
    if($(".power_off").html()=="开机"){
        $(".power_off").html("关机");
    }
    $(".washBtn").click(function(event){
        event.preventDefault();  
    });
}
//水满状态3
function fullWater(){
    all_hide();
    $(".fullWater1").show();
    $(".fullWater2").show();
    $(".textList").show();
    $('.washBtn').html("冲洗");
    $(".washBtn").css("backgroundColor","#fff");
    if($(".power_off").html()=="开机"){
        $(".power_off").html("关机");
    }
}
//检修状态4
function service(){
    all_hide();
    $(".service").show();
    $(".textList").show();
    $('.washBtn').html("冲洗");
    $(".washBtn").css("backgroundColor","#ccc");
    if($(".power_off").html()=="开机"){
        $(".power_off").html("关机");
    }
    $(".washBtn").click(function(event){
        event.preventDefault();  
    });
}
//冲洗5
function wash(){
    all_hide();
    $(".wash").show();
    $(".textList").show();
    $(".washBtn").html("取消冲洗");
    $(".washBtn").css("backgroundColor","#fff");
    if($(".power_off").html()=="开机"){
        $(".power_off").html("关机");
    }
}
//欠费6
function arrearage(){
    all_hide();
    $(".arrearage").show();
    $(".arrearageText").show();
    $(".washBtn").html("冲洗");
    $(".washBtn").css("backgroundColor","#fff");
    if($(".power_off").html()=="开机"){
        $(".power_off").html("关机");
    }
}
//关机7
function shutDown(){
    all_hide();
    $(".offTxtBg").show();
    $(".washBtn").html("冲洗");
    $(".washBtn").css("backgroundColor","#ccc");
    $(".power_off").html("开机");
}
//漏水8
function leakage(){
    all_hide();
    $(".leakage_whisht").show();
    $(".leakage_act").show();
    $(".washBtn").html("冲洗");
    $(".washBtn").css("backgroundColor","#ccc");
    $(".power_off").html("开机");
}
//停机9
function halt(){
    all_hide();
    $(".halt").show();
    $(".washBtn").html("冲洗");
    $(".washBtn").css("backgroundColor","#ccc");
    $(".power_off").html("关机");
}
//离线
function  offLine(){
    all_hide();
    $(".textList").show();
    $(".washBtn").html("冲洗");
    $(".washBtn").css("backgroundColor","#ccc");
    $(".power_off").html("开机");
    $(".TdsNumValue").html("000");
    $(".rawwaterNum").html("000");
    $(".surplusNum").html("0");
    $(".percent1").val("0");
    $(".percent2").val("0");
    $(".percent3").val("0");
    $(".percent4").val("0");
    $(".percent5").val("0");
    $(".washBtn").click(function(event){
        event.preventDefault();  
    });
}

//页面加载时
window.onload=function(){
    //水机状态切换
    var DecStatus = $('.decStatus').val();
    var val = $(".power_off").html();
    if(DecStatus==1){//制水
        addWater();
    }else if(DecStatus==2){//缺水
        lessWater();
    }else if(DecStatus==3){//水满
        fullWater();
    }else if(DecStatus==4){//检修
        service();
    }else if(DecStatus==5){//冲洗
        wash();
    }else if(DecStatus==6){//欠费
        arrearage();
    }else if(DecStatus==7){//关机
        shutDown();
    }else if(DecStatus==8){//漏水
        leakage();
    }else if(DecStatus==9){//停机
        halt();
    }else{
        addWater();
        filterFn();
    }
    //页面加载时判断页面是否离线
    if($(".statusName").html()=="离线"){
        offLine();
    }
    if($(".statusName").html()!="离线"&&$(".statusName").html()!="关机"){
        setTimeout(function(){
            if($(".power_off").html()=="关机"){
                $(".power_off").html("解锁");
            }
        }, 10000);
    }
    //点击开机/关机/解锁按钮
    $(".power_off").click(function(){
        var val = $(this).html();
        if(val=="关机"){
            var command ="power_off";
        }else if(val=="开机"){
            var command = "power_on";
        }else{
            var command = "unlock";
            $(".power_off").html("关机");
        }
        if(command!="unlock"){
            $.ajax({
                url:"/api/device/control",
                type:"post",
                dataType:"json",
                data:{command:command},
                success:function(data){
                    if(data.status.errCode == 0){
                    }else if(data.status.errCode == 20005){//没有绑定水机
                        window.location.href = "/device/bind";
                        hint(data.status.message);
                        
                    }else{
                        hint(data.status.message);
                        if(data.status.errCode==20002){//设备离线
                            all_hide();
                            $('.offTxtBg').show();
                        }
                    }
                },
                error:function(jqXHR, textStatus, errorThrown){
                    hint(jqXHR.responseText);   
                }
            });
        } 
        if($(".statusName").html()!="离线"&&$(".statusName").html()!="关机"){
            setTimeout(function(){
                if($(".power_off").html()=="关机"){
                    $(".power_off").html("解锁");
                }
            }, 10000);
        }
    });
    //点击冲洗按钮
    $('.washBtn').click(function(event){
        var val = $(".power_off").html();
        if(val == "开机")
        {
            $(".washBtn").css("backgroundColor","#ccc");
            event.preventDefault();
        }else
        {
            $(".washBtn").css("backgroundColor","#ccc");
            if($(this).html() == "冲洗"){
                var command = "wash";     
            }else{
                var command = "wash_cancel";    
            }
            $.ajax({
                url:"/api/device/control",
                type:"post",
                dataType:"json",
                data:{command:command},
                success:function(data){
                    if(data.status['errCode'] == 0){
                    }else if(data.status.errCode == 20005){//没有绑定水机
                        window.location.href = "/device/bind";
                        hint(data.status.message);
                    }else{
                        hint(data.status.message);
                    }
                },
                error:function(jqXHR, textStatus, errorThrown){
                    hint(jqXHR.responseText);
                }
            });
        }
    });
    //index页面滤芯弹出框js
    $(".filter_bg").height($(window).height());
    $(".circle").click(function(){
        $(".filter_bg").show();
        $(".residueNum").html($(this).children("strong").html());
        $(".callOff").unbind('click').click(function(){
            $(".filter_bg").hide();
        });
        var i;
        i=$(this).index()+1;
        $(".reset").unbind('click').click(function(){
            $('.undbing_bg').show();
            $('.undbing_bg').height($(window).height());
            $('.no_btn').unbind('click').click(function(){
                $('.undbing_bg').hide();
            });
            $('.yes_btn').unbind('click').click(function(){
                $.ajax({
                    url:"/api/device/control",
                    type:"post",
                    data:{command:"reset_filter", num:i},
                    success:function(data){
                        $('.undbing_bg').hide();
                        $('.filter_bg').hide();
                        if(data.status.errCode == 0){
                            hint("操作成功！");
                        }else
                        {
                            hint("操作失败，请重新操作或联系售后人员！");
                        }
                    }
                });
            });
        });
    });
    //index exchangePart js
    var index=0;
    $(".shopLog").click(function(){
        if(index==0){
            $(this).css("-webkit-transform","scaleX(-1)");
            $(this).css("transform","scaleX(-1)");
            $(".shopping").animate({"right":"-0rem"},200);
            $(".surplus").animate({"marginLeft":"1rem"},200);
            index=1;
        }else
        {
            $(this).css("-webkit-transform","scaleX(1)");
            $(this).css("transform","scaleX(1)");
            $(".shopping").animate({"right":"-6rem"},200);
            $(".surplus").animate({"marginLeft":"4rem"},200);
            index=0;
        }   
    });
};
